# coding: UTF-8
# Filename : chain_part_api.py
# Company : imedia
# Author : rose 
# -*-coding:utf-8 -*-
from api.common.common import *
from api.common import mysql,log,utils,httputils,const
#import mysql,log,utils,httputils,const
import chain_part_data_model

common_sql = '''
select `name`, address, tel, longitude, latitude, description, store_in_app, id, images, 
list_thumb, city_id, (select tb1.name from im_city tb1 where tb1.id = city_id),
summary
from chain_part
'''

#替换字符
#sbu_flag 区分是否需要过滤html字符
#ratio适配信息
#is_thumb是否是缩略图
def replace_body(obj, sub_flag, ratio, is_thumb):
    if obj == None : return ''
    body_template = chain_part_data_model.imedia_body
    body_template = body_template.replace('{name}', str(obj[0]))
    body_template = body_template.replace('{address}', str(obj[1]))
    body_template = body_template.replace('{tel}', str(obj[2]))
    body_template = body_template.replace('{longitude}', str(obj[3]))
    body_template = body_template.replace('{latitude}', str(obj[4]))
    if sub_flag :
        body_template = body_template.replace('{description}', utils.get_detail_text(str(obj[5])))
    else:
        body_template = body_template.replace('{description}', str(obj[5]))
    body_template = body_template.replace('{storeinapp}', str(obj[6]))
    body_template = body_template.replace('{id}', str(obj[7]))
    
    body_template = body_template.replace('{images}', image_path(obj[8], ratio, False))
    body_template = body_template.replace('{thumb}', image_path(obj[9], ratio, True))
    body_template = body_template.replace('{city_id}', str(obj[10]))
    body_template = body_template.replace('{city_name}', str(obj[11]))
    body_template = body_template.replace('{summary}', str(obj[12]))
    return body_template    
  
def get_detail_str(part_id, ratio):
    #数据库查询
    sql = common_sql + '''
    where id = %s
    and active = 1
    '''
    obj = mysql.get(sql, [int(part_id)])
    return replace_body(obj, False, ratio, False)

#判断是否为空
def is_full(obj):
    return obj != None and str(obj).strip() != ''

#获取中间数据体
def get_body_str(cus_id, size, pagenum, arrays, ratio, city, storeinapp='0'):
    if arrays == None or len(arrays) < 3: return ''
    #封装storeinapp条件
    condition = storeinapp
    longitude = arrays[0]
    latitude = arrays[1]
    radius = arrays[2]
    #判断city 存在
    city_sql = ''
    if(is_full(city)):
        sql = '''select id from im_city where up>1 and name= %s'''
        record = mysql.get(sql, [city])
        if(record != None):
            city_sql = 'and city_id = '+str(record[0])
    
    #需要地理信息查询
    if is_full(longitude) and is_full(latitude) and is_full(radius):
        sql ='''select `name`, address, tel, longitude, latitude, description, store_in_app, id, images, list_thumb, city_id,
                (select tb1.name from im_city tb1 where tb1.id = city_id),
                ( 6371 * acos( cos( radians(%s) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(%s) ) + sin( radians(%s) ) * sin( radians( latitude ) ) ) ) 
                as distance 
                from chain_part
                where cus_id = %s ''' + city_sql +'''
                and active = 1
                and store_in_app in ({condition})
                having distance < %s
                order by distance
                limit %s, %s+
            '''
        sql = sql.replace('{condition}', condition)
        #获取起始行
        start_row = utils.get_star_row(size, pagenum)
        param = [longitude, latitude, longitude, int(cus_id), radius, start_row, int(size)]
        rsts = mysql.doSearch(sql, param)
        body_str = ''
        for obj in rsts:
            body_str += replace_body(obj, True, ratio, True)
        return body_str
    #正常查询
    else:
        #sql
        sql = common_sql + '''
            where cus_id = %s ''' + city_sql +'''
            and active = 1
            and store_in_app in ({condition})
            order by id desc
            limit %s, %s
            '''
        sql = sql.replace('{condition}', condition)
        #获取起始行
        start_row = utils.get_star_row(size, pagenum)
        param = [int(cus_id), start_row, int(size)]
        rsts = mysql.doSearch(sql, param)
        body_str = ''
        for obj in rsts:
            body_str += replace_body(obj, True, ratio, True)
        return body_str


#获取详细列表http://api.imedia.com/app/part/list
def chain_part_list(request):
    #记录用户脚印(必做动作)
    httputils.footprint(request)
    #获取请求参数
    cus_id = httputils.post(request, 'cus_id')
    longitude = httputils.post(request, 'longitude')
    latitude = httputils.post(request, 'latitude')
    radius = httputils.post(request, 'radius')
    ratio = httputils.post(request, 'ratio')
    #获取城市id
    city = httputils.post(request, 'city')
    #获取storeinapp
    storeinapp = httputils.post(request, 'storeinapp')
    if storeinapp == None or storeinapp.strip() == '': storeinapp = '0'
    storeinapp_arr = storeinapp.split(',')
    for storeinapp_obj in storeinapp_arr:
        if not utils.is_num(storeinapp_obj): storeinapp = '0'
    
    size = httputils.post(request, 'size')
    pagenum = httputils.post(request, 'pagenum')
    if not utils.is_num(size): size = 5
    if not utils.is_num(pagenum): pagenum = 1
    if not utils.is_num(cus_id): cus_id = 1
    #通信验证
    if validate(request):
        return validate(request)
    #中间模板段
    output = ''
    output += chain_part_data_model.imedia_start 
    output += get_body_str(cus_id, size, pagenum, (longitude, latitude, radius), ratio, city, storeinapp)
    output += chain_part_data_model.imedia_end
    #初始化xml返回
    return response(output)

#获取单个信息http://api.imedia.com/app/part
def chain_part_detail(request):
    #记录用户脚印(必做动作)
    httputils.footprint(request)
    #通信验证
    if validate(request):
        return validate(request)
    
    part_id = httputils.post(request, 'part_id')
    ratio = httputils.post(request, 'ratio')
    id_array = part_id.split(',')
    output = ''
    output += chain_part_data_model.imedia_start
    for obj_id in id_array:
        if not utils.is_num(obj_id): obj_id = 0 #做验证防止异常发生
        output += get_detail_str(obj_id, ratio)
    output += chain_part_data_model.imedia_end
    return response(output)


